using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.IO.Ports;

namespace nxtBlueTooth
{
    public partial class Form1 : Form
    {
        private SerialPort BluetoothConnection = new SerialPort();
        private MemoryStream ms;
        private TextWriter tw;
        private BackgroundWorker bgw;
        public Form1()
        {
            InitializeComponent();
            bgw = new BackgroundWorker();
            bgw.WorkerSupportsCancellation = true;
            bgw.DoWork += new DoWorkEventHandler(bgw_DoWork);
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (tw != null)
                tw.Close();
            if (ms != null)
                ms.Close();
        }

        void bgw_DoWork(object sender, DoWorkEventArgs e)
        {
            tw.WriteLine("tick,compass,irdir,ir3,light,ultra");
            //bool doAdd = true;
            while (BluetoothConnection.IsOpen)
            {
                //doAdd = true;
                int tick = readInt();
                int compass = readInt();
                int irDir = readInt();
                int ir3 = readInt();
                int light = readInt();
                int ultra = readInt();
                //int end = readInt();
                //if (end != 255 * 255)
                //    doAdd = false;
                //while (end != 255 * 255)
                //{
                //    end = readInt();
                //}

                labelTick.Invoke(new MethodInvoker(delegate { labelTick.Text = tick.ToString(); }));
                labelCompass.Invoke(new MethodInvoker(delegate { labelCompass.Text = compass.ToString(); }));
                labelIRDir.Invoke(new MethodInvoker(delegate { labelIRDir.Text = irDir.ToString(); }));
                labelIR3.Invoke(new MethodInvoker(delegate { labelIR3.Text = ir3.ToString(); }));
                labelLight.Invoke(new MethodInvoker(delegate { labelLight.Text = light.ToString(); }));
                labelUltra.Invoke(new MethodInvoker(delegate { labelUltra.Text = ultra.ToString(); }));


                //if (doAdd)
                {
                    tw.WriteLine(String.Format("{0},{1},{2},{3},{4},{5}", tick, compass, irDir, ir3, light, ultra));
                    //if (tick % 100 == 0)
                    //addRow(tick, compass, ir, ultra, light);
                }
            }
        }

        private void buttonReadMailbox_Click(object sender, EventArgs e)
        {
            if (tw != null)
                tw.Close();
            if (ms != null)
                ms.Close();
            ms = new MemoryStream();
            tw = new StreamWriter(ms);

            bgw.RunWorkerAsync();
        }

        private int readInt()
        {
            try
            {
                int length = (BluetoothConnection.ReadByte() * 256) + BluetoothConnection.ReadByte();
                return (BluetoothConnection.ReadByte() * 256) + BluetoothConnection.ReadByte();
            }
            catch (System.InvalidOperationException ex)
            {
                bgw.CancelAsync();
                displayError(ex.ToString());
            }
            catch (TimeoutException ex)
            {
                bgw.CancelAsync();
                displayError(ex.ToString());
            }
            catch (IOException ex)
            {
                bgw.CancelAsync();
                displayError(ex.ToString());
            }
            return 0;
        }

        private void displayError(string s)
        {
            labelTick.Invoke(new MethodInvoker(delegate { textBoxError.Text = s; }));
        }

        private void buttonConnect_Click(object sender, EventArgs e)
        {
            this.buttonConnect.Enabled = false;
            if (BluetoothConnection.IsOpen)
            {
                this.buttonReadMailbox.Enabled = false;
                BluetoothConnection.Close();
                this.buttonConnect.Text = "Connect";
            }
            else
            {
                this.buttonConnect.Text = "Disconnect";
                this.BluetoothConnection.PortName = this.textBox1.Text.Trim();
                this.buttonReadMailbox.Enabled = true;
                try
                {
                    BluetoothConnection.Open();
                }
                catch (IOException ex)
                {
                    textBoxError.Text = ex.ToString();
                }
                BluetoothConnection.ReadTimeout = 1500;
                buttonReadMailbox_Click(null, null); //start reading mailbox on connect
            }
            this.buttonConnect.Enabled = true;
        }

        private void buttonWrite_Click(object sender, EventArgs e)
        {
            string filename = DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + ".txt";
            FileStream fs = File.OpenWrite(filename);
            ms.WriteTo(fs);
            fs.Close();
        }
    }
}